#include <Arduino.h>
#include<SPI.h>
#include<NTPClient.h>
#include<ESP8266WiFi.h>
#include<WiFiUdp.h>

const char *ssid = "ZNet";
const char *password = "5678ping";
const int dio = 13;
const int clk = 14;
const int cs = 15;
const int en = 16;

WiFiUDP udp;
NTPClient timeClient(udp,"ntp1.aliyun.com",60*60*8, 30*60*1000);
SPIClass vspi(SPI);
byte hour,minute,con,lastsecond,second,count;  //con用来控制当前显示的数位，count用来控制秒点亮的时间
int cc;
unsigned long long lastmillis;
//使用esp8266默认的SPI端口
byte numbers[2][10]={0b01000000,0b01111001,0b00100100,0b00110000,0b00011001,0b00010010,0b00000010,0b01111000,0b00000000,0b00010000,
                     0b11000000,0b11111001,0b10100100,0b10110000,0b10011001,0b10010010,0b10000010,0b11111000,0b10000000,0b10010000};

void transmission(byte digit,byte num)
{
  if(lastsecond!=second)
  {
    //新的一秒，点亮秒点
    vspi.transfer(1<<digit);
    vspi.transfer(numbers[1][num]);
    digitalWrite(cs,LOW);
    digitalWrite(cs,HIGH);
    count++;
    if(count==249)
    {
      count=0;
      lastsecond = second;
    }
  }
  else
  {
      //后半秒，熄灭秒点
      vspi.transfer(1<<digit);
      vspi.transfer(numbers[0][num]);
      digitalWrite(cs,LOW);
      digitalWrite(cs,HIGH);
 
  }

}
void timeprint()
{
  if(millis()-lastmillis>=2)
  {
    switch(con)
    {
      case 0:
        if(hour/10)
          transmission(con,hour/10);
        break;
      case 1:
        transmission(con,hour%10);
        break;
      case 2:
        transmission(con,minute/10);
        break;
      case 3:
        transmission(con,minute%10);
        break;
    }
    con++;
    if(con==4)
      con=0;
    lastmillis = millis();
    
  }

}
void setup() {
  
  pinMode(cs,OUTPUT);
  pinMode(en,OUTPUT);
  digitalWrite(en,HIGH);  //显示输出无效  
  
  vspi.begin();
  Serial.begin(9600);
  WiFi.begin(ssid, password);
  Serial.print("Connecting");
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }
  Serial.println("WiFi Connected.");
  hour=5;
  minute = 34;
  con=0;
  digitalWrite(en,LOW); //显示输出有效
}
void loop() {
  // put your main code here, to run repeatedly:
  timeprint();
  
  timeClient.update();
  hour = timeClient.getHours();
  minute = timeClient.getMinutes();
  second = timeClient.getSeconds(); 
  if(millis()<lastmillis) //millis（）归零后更新
    lastmillis = millis();
 
  
}